3 // Keychain Circle Notification
5 // Created by J Osborne on 2/21/13.
9 #import "KNAppDelegate.h"
10 #import "KDSecCircle.h"
11 #import "KDCirclePeer.h"
12 #import "NSDictionary+compactDescription.h"
13 #import <AOSUI/NSImageAdditions.h>
14 #import <AppleSystemInfo/AppleSystemInfo.h>
15 #import <Security/SecFrameworkStrings.h>
17 #import <AOSAccounts/MobileMePrefsCoreAEPrivate.h>
18 #import <AOSAccounts/MobileMePrefsCore.h>
20 static char *kLaunchLaterXPCName = "com.apple.security.Keychain-Circle-Notification-TICK";
22 @implementation KNAppDelegate
24 static NSUserNotificationCenter *appropriateNotificationCenter()
26 return [NSUserNotificationCenter _centerForIdentifier:@"com.apple.security.keychain-circle-notification" type:_NSUserNotificationCenterTypeSystem];
29 -(void)notifyiCloudPreferencesAbout:(NSString *)eventName;
31 if (nil == eventName) {
35 NSString *account = (__bridge NSString *)(MMCopyLoggedInAccount());
36 NSLog(@"notifyiCloudPreferencesAbout %@", eventName);
39 BOOL createdAEDesc = createAEDescWithAEActionAndAccountID((__bridge NSString *)kMMServiceIDKeychainSync, eventName, account, &aeDesc);
43 LSLaunchURLSpec lsSpec;
46 lsSpec.itemURLs = (__bridge CFArrayRef)([NSArray arrayWithObject:[NSURL fileURLWithPath:@"/System/Library/PreferencePanes/iCloudPref.prefPane"]]);
47 lsSpec.passThruParams = &aeDesc;
48 lsSpec.launchFlags = kLSLaunchDefaults | kLSLaunchAsync;
49 lsSpec.asyncRefCon = NULL;
51 err = LSOpenFromURLSpec(&lsSpec, NULL);
54 NSLog(@"Can't send event %@, err=%d", eventName, err);
56 AEDisposeDesc(&aeDesc);
60 NSLog(@"unable to create and send aedesc for account: '%@' and action: '%@'\n", account, eventName);
64 -(void)showiCloudPrefrences
66 static NSAppleScript *script = nil;
68 script = [[NSAppleScript alloc] initWithSource:@"tell application \"System Preferences\"\n\
70 set the current pane to pane id \"com.apple.preferences.icloud\"\n\
74 NSDictionary *appleScriptError = nil;
75 [script executeAndReturnError:&appleScriptError];
77 if (appleScriptError) {
78 NSLog(@"appleScriptError: %@", appleScriptError);
80 NSLog(@"NO appleScript error");
86 NSDate *nowish = [NSDate new];
87 self.state = [KNPersistantState loadFromStorage];
88 if ([nowish compare:self.state.pendingApplicationReminder] != NSOrderedAscending) {
89 NSLog(@"REMINDER TIME: %@ >>> %@", nowish, self.state.pendingApplicationReminder);
90 // self.circle.rawStatus might not be valid yet
91 if (SOSCCThisDeviceIsInCircle(NULL) == kSOSCCRequestPending) {
92 // Still have a request pending, send reminder, and also in addtion to the UI
93 // we need to send a notification for iCloud pref pane to pick up
95 CFNotificationCenterPostNotificationWithOptions(CFNotificationCenterGetDistributedCenter(), CFSTR("com.apple.security.secureobjectsync.pendingApplicationReminder"), (__bridge const void *)([self.state.applcationDate description]), NULL, 0);
97 [self postApplicationReminder];
98 self.state.pendingApplicationReminder = [self.state.applcationDate dateByAddingTimeInterval:[self getPendingApplicationReminderInterval]];
99 [self.state writeToStorage];
104 -(void)scheduleActivityAt:(NSDate*)time
106 if ([time compare:[NSDate distantFuture]] != NSOrderedSame) {
107 NSTimeInterval howSoon = [time timeIntervalSinceNow];
109 [self scheduleActivityIn:howSoon];
116 -(void)scheduleActivityIn:(int)alertInterval
118 xpc_object_t options = xpc_dictionary_create(NULL, NULL, 0);
119 xpc_dictionary_set_uint64(options, XPC_ACTIVITY_DELAY, alertInterval);
120 xpc_dictionary_set_uint64(options, XPC_ACTIVITY_GRACE_PERIOD, XPC_ACTIVITY_INTERVAL_1_MIN);
121 xpc_dictionary_set_bool(options, XPC_ACTIVITY_REPEATING, false);
122 xpc_dictionary_set_bool(options, XPC_ACTIVITY_ALLOW_BATTERY, true);
123 xpc_dictionary_set_string(options, XPC_ACTIVITY_PRIORITY, XPC_ACTIVITY_PRIORITY_UTILITY);
125 xpc_activity_register(kLaunchLaterXPCName, options, ^(xpc_activity_t activity) {
130 -(NSTimeInterval)getPendingApplicationReminderInterval
132 if (self.state.pendingApplicationReminderInterval) {
133 return [self.state.pendingApplicationReminderInterval doubleValue];
139 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
141 appropriateNotificationCenter().delegate = self;
143 NSLog(@"Posted at launch: %@", appropriateNotificationCenter().deliveredNotifications);
145 self.viewedIds = [NSMutableSet new];
146 self.circle = [KDSecCircle new];
147 self.state = [KNPersistantState loadFromStorage];
148 KNAppDelegate *me = self;
150 [self.circle addChangeCallback:^{
151 me.state = [KNPersistantState loadFromStorage];
152 if ((me.state.lastCircleStatus == kSOSCCInCircle && !me.circle.isInCircle) || me.state.debugLeftReason) {
153 enum DepartureReason reason = kSOSNeverLeftCircle;
154 if (me.state.debugLeftReason) {
155 reason = [me.state.debugLeftReason intValue];
156 me.state.debugLeftReason = nil;
158 CFErrorRef err = NULL;
159 reason = SOSCCGetLastDepartureReason(&err);
160 if (reason == kSOSDepartureReasonError) {
161 NSLog(@"SOSCCGetLastDepartureReason err: %@", err);
165 //NSString *model = (__bridge NSString *)(ASI_CopyComputerModelName(FALSE));
166 NSString *body = nil;
168 case kSOSDepartureReasonError:
169 case kSOSNeverLeftCircle:
170 case kSOSWithdrewMembership:
174 NSLog(@"Unknown departure reason %d", reason);
175 // fallthrough on purpose
177 case kSOSMembershipRevoked:
178 case kSOSLeftUntrustedCircle:
179 body = NSLocalizedString(@"Approve this Mac from another device to use iCloud Keychain.", @"Body for iCloud Keychain Reset notification");
182 [me.state writeToStorage];
183 NSLog(@"departure reason %d, body=%@", reason, body);
185 [me postKickedOutWithMessage: body];
191 if (me.state.lastCircleStatus != kSOSCCRequestPending && me.circle.rawStatus == kSOSCCRequestPending) {
192 NSLog(@"Entered RequestPending");
193 NSDate *nowish = [NSDate new];
194 me.state.applcationDate = nowish;
195 me.state.pendingApplicationReminder = [me.state.applcationDate dateByAddingTimeInterval:[me getPendingApplicationReminderInterval]];
196 [me.state writeToStorage];
197 [me scheduleActivityAt:me.state.pendingApplicationReminder];
200 NSMutableSet *applicantIds = [NSMutableSet new];
201 for (KDCirclePeer *applicant in me.circle.applicants) {
202 if (!me.circle.isInCircle) {
203 // We don't want to yammer on about circles we aren't in,
204 // and we don't want to be extra confusing announcing our
205 // own join requests as if the user could approve them
209 [me postForApplicant:applicant];
210 [applicantIds addObject:applicant.idString];
213 NSUserNotificationCenter *notificationCenter = appropriateNotificationCenter();
214 NSLog(@"Checking validity of %lu notes", (unsigned long)notificationCenter.deliveredNotifications.count);
215 for (NSUserNotification *note in notificationCenter.deliveredNotifications) {
216 if (note.userInfo[@"applicantId"] && ![applicantIds containsObject:note.userInfo[@"applicantId"]]) {
217 NSLog(@"No longer an applicant (%@) for %@ (I=%@)", note.userInfo[@"applicantId"], note, [note.userInfo compactDescription]);
218 [notificationCenter removeDeliveredNotification:note];
220 NSLog(@"Still an applicant (%@) for %@ (I=%@)", note.userInfo[@"applicantId"], note, [note.userInfo compactDescription]);
224 me.state.lastCircleStatus = me.circle.rawStatus;
226 [me.state writeToStorage];
229 [me scheduleActivityAt:me.state.pendingApplicationReminder];
232 -(BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification
237 -(void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
239 if (notification.activationType == NSUserNotificationActivationTypeActionButtonClicked) {
240 [self notifyiCloudPreferencesAbout:notification.userInfo[@"Activate"]];
243 // The "Later" seems handled Ok without doing anything here, but KickedOut & other special items need an action
244 if (notification.userInfo[@"SPECIAL"]) {
245 NSLog(@"ACTIVATED (remove): %@", notification);
246 [appropriateNotificationCenter() removeDeliveredNotification:notification];
248 NSLog(@"ACTIVATED (NOT removed): %@", notification);
252 -(void)userNotificationCenter:(NSUserNotificationCenter *)center didDismissAlert:(NSUserNotification *)notification
254 [self notifyiCloudPreferencesAbout:notification.userInfo[@"Dismiss"]];
256 if (!notification.userInfo[@"SPECIAL"]) {
257 // If we don't do anything here & another notification comes in we
258 // will repost the alert, which will be dumb.
259 id applicantId = notification.userInfo[@"applicantId"];
260 if (applicantId != nil) {
261 [self.viewedIds addObject:applicantId];
263 NSLog(@"DISMISS (t) %@", notification);
265 NSLog(@"DISMISS (f) %@", notification);
266 [appropriateNotificationCenter() removeDeliveredNotification:notification];
270 -(void)postForApplicant:(KDCirclePeer*)applicant
272 static int postCount = 0;
274 if ([self.viewedIds containsObject:applicant.idString]) {
275 NSLog(@"Already viewed %@, skipping", applicant);
279 NSUserNotificationCenter *noteCenter = appropriateNotificationCenter();
280 for (NSUserNotification *note in noteCenter.deliveredNotifications) {
281 if ([applicant.idString isEqualToString:note.userInfo[@"applicantId"]]) {
282 if (note.isPresented) {
283 NSLog(@"Already posted&presented: %@ (I=%@)", note, note.userInfo);
286 NSLog(@"Already posted, but not presented: %@ (I=%@)", note, note.userInfo);
291 NSUserNotification *note = [NSUserNotification new];
293 // Genstrings command line is: genstrings -o en.lproj -u KNAppDelegate.m
294 note.title = [NSString stringWithFormat:NSLocalizedString(@"iCloud Keychain", @"Title for new keychain syncing device notification")];
295 note.informativeText = [NSString stringWithFormat:NSLocalizedString(@"\\U201C%1$@\\U201D wants to use your passwords.", @"Message text for new keychain syncing device notification"), applicant.name];
297 note.hasActionButton = YES;
298 note._displayStyle = _NSUserNotificationDisplayStyleAlert;
299 note._identityImage = [NSImage bundleImage];
300 note._identityImageHasBorder = NO;
301 note._actionButtonIsSnooze = YES;
302 note.actionButtonTitle = NSLocalizedString(@"Later", @"Button label to dismiss device notification");
303 note.otherButtonTitle = NSLocalizedString(@"View", @"Button label to view device notification");
305 note.identifier = [[NSUUID new] UUIDString];
307 note.userInfo = @{@"applicantName": applicant.name,
308 @"applicantId": applicant.idString,
309 @"Dismiss": (__bridge NSString *)kMMPropertyKeychainAADetailsAEAction,
312 NSLog(@"About to post#%d/%lu (%@): %@", postCount, (unsigned long)noteCenter.deliveredNotifications.count, applicant.idString, note);
313 [appropriateNotificationCenter() deliverNotification:note];
318 -(void)postKickedOutWithMessage:(NSString*)body
320 NSUserNotificationCenter *noteCenter = appropriateNotificationCenter();
321 for (NSUserNotification *note in noteCenter.deliveredNotifications) {
322 if (note.userInfo[@"KickedOut"]) {
323 if (note.isPresented) {
324 NSLog(@"Already posted&presented (removing): %@", note);
325 [appropriateNotificationCenter() removeDeliveredNotification: note];
327 NSLog(@"Already posted, but not presented: %@", note);
332 NSUserNotification *note = [NSUserNotification new];
334 note.title = NSLocalizedString(@"iCloud Keychain Was Reset", @"Title for iCloud Keychain Reset notification");
335 note.informativeText = body; // Already LOCed
337 note._identityImage = [NSImage bundleImage];
338 note._identityImageHasBorder = NO;
339 note.otherButtonTitle = NSLocalizedString(@"Close", @"Close button");
340 note.actionButtonTitle = NSLocalizedString(@"Options", @"Options Button");
342 note.identifier = [[NSUUID new] UUIDString];
344 note.userInfo = @{@"KickedOut": @1,
346 @"Activate": (__bridge NSString *)kMMPropertyKeychainMRDetailsAEAction,
349 NSLog(@"About to post#-/%lu (KICKOUT): %@", (unsigned long)noteCenter.deliveredNotifications.count, note);
350 [appropriateNotificationCenter() deliverNotification:note];
353 -(void)postApplicationReminder
355 NSUserNotificationCenter *noteCenter = appropriateNotificationCenter();
356 for (NSUserNotification *note in noteCenter.deliveredNotifications) {
357 if (note.userInfo[@"ApplicationReminder"]) {
358 if (note.isPresented) {
359 NSLog(@"Already posted&presented (removing): %@", note);
360 [appropriateNotificationCenter() removeDeliveredNotification: note];
362 NSLog(@"Already posted, but not presented: %@", note);
367 NSUserNotification *note = [NSUserNotification new];
369 note.title = NSLocalizedString(@"iCloud Keychain", @"Title for iCloud Keychain Application still pending (from this device) reminder");
370 note.informativeText = NSLocalizedString(@"Approve this Mac from another device to use iCloud Keychain.", @"Body text for iCloud Keychain Application still pending (from this device) reminder");
372 note._identityImage = [NSImage bundleImage];
373 note._identityImageHasBorder = NO;
374 note.otherButtonTitle = NSLocalizedString(@"Close", @"Close button");
375 note.actionButtonTitle = NSLocalizedString(@"Options", @"Options Button");
377 note.identifier = [[NSUUID new] UUIDString];
379 note.userInfo = @{@"ApplicationReminder": @1,
381 @"Activate": (__bridge NSString *)kMMPropertyKeychainWADetailsAEAction,
384 NSLog(@"About to post#-/%lu (REMINDER): %@", (unsigned long)noteCenter.deliveredNotifications.count, note);
385 [appropriateNotificationCenter() deliverNotification:note];